#!/usr/bin/env python3
# encoding=utf-8

import os
import shutil
from word_by_docx import fill_doccell_by_excelinfo
from word_by_win32 import fill_win32cell_by_excelinfo
from word_with_image import replace_word_png, word_to_image
from commom_api import get_temp_dirpath, get_doc_dirpath, get_product_name_prefix, get_doc_fill_base_info, check_code_in_list

import logging
logger = logging.getLogger(__name__)

def get_word_name_by_xlsinfo(xlsinfo):
    docname, mode = get_doc_fill_base_info(xlsinfo['code'], xlsinfo['daterange'][0])
    if docname == None:
        logger.error(f"请先在confi.json配置{xlsinfo['code']}产品周报的模版")
        return None
    docname = '产品周报.docx'
    wordname = os.path.basename(xlsinfo['excel']).replace('净值表', '产品周报').replace('.xlsx', '.docx')
    # wordname = get_product_name_prefix(os.path.basename(xlsinfo['excel']))
    # wordname = f'{wordname}产品周报%s-%s.docx' % (xlsinfo['daterange'][0].strftime("%Y.%m.%d"), xlsinfo['daterange'][2].replace('-', '.'))
    tempword = os.path.join(get_temp_dirpath(), wordname)
    orgword = os.path.join(docname)
    if not os.path.exists(orgword):
        orgword = os.path.join(get_doc_dirpath(), docname)
        if not os.path.exists(orgword):
            orgword = os.path.join('dist', docname)
            if not os.path.exists(orgword):
                logger.error(f"请先配置产品周报的模版，并命名为{docname}")
                return None
    if not os.path.exists(tempword):
        shutil.copyfile(orgword, tempword)
    return tempword

def fill_word_with_excel_value(excelwb, xlsinfo):
    wordpath = get_word_name_by_xlsinfo(xlsinfo)
    if wordpath == None or not os.path.exists(wordpath):
        logger.warning(f"not wordpath for {xlsinfo['sheetname']}")
        return None
    
    try:
        if hasattr(excelwb, 'Worksheets'):
            sheet = excelwb.Worksheets[xlsinfo['sheetname']]
            fill_win32cell_by_excelinfo(sheet, wordpath, xlsinfo)
        elif hasattr(excelwb, 'sheets'):
            sheet = excelwb.sheets[xlsinfo['sheetname']]
            fill_doccell_by_excelinfo(sheet, wordpath, xlsinfo)
        else:
            logger.warning(f"error Worksheets for {xlsinfo['sheetname']}")
            return None
        docname, rect = get_doc_fill_base_info(xlsinfo['code'], xlsinfo['daterange'][0], key='rect')
        if check_code_in_list(xlsinfo['code'], xlsinfo['daterange'][0], xlsinfo['keepword']) == True:
            return (wordpath, rect, True)
        else:
            return (wordpath, rect, False)
    except Exception as e:
        logging.error(f"myword fill error[{e}] {xlsinfo['sheetname']}")
        return None

if __name__=="__main__":
    wordpath = os.path.join('H:\\study\\mail_study\\doc\\temp', '雷菱吉量3号产品周报.docx')
    # word_to_image(wordpath, 'XJ723A')
    # os._exit(-1)

    xlsinfo = {}
    xlsinfo['code'] = 'XJ723A'
    xlsinfo['maxpos'] = [32, 10]
    xlsinfo['flexiblepos'] = [7, 10]
    xlsinfo['sheetname'] = f'雷菱吉量3号（周）'
    xlsinfo['excel'] = os.path.join('H:\\study\\mail_study\\doc\\temp', f'雷菱吉量3号净值表2022.12.23-2025.2.24.xlsx')
    
